import qs from 'query-string'
import { useMemo } from 'react'
import { useLocation } from 'react-router'

type SourceType = 'search' | 'hash' | 'state'
const DEFAULT_FROMS: SourceType[] = ['search']

export default function useLocationParams(froms: SourceType[] = DEFAULT_FROMS) {
  const { search: search_str, hash: hash_str, state } = useLocation()
  return useMemo(() => {
    let search: any;
    let hash: any;
    let mix: any = {}
    for (const f of froms) {
      switch (f) {
        case 'search':
          if (!search) {
            search = qs.parse(search_str);
            Object.assign(mix, search);
          }
          break;
        case 'hash':
          if (!hash) {
            hash = qs.parse(hash_str);
            Object.assign(mix, hash);
          }
          break;
        case 'state':
          Object.assign(mix, state);
          break;
      }
    }
    const str = (k: string) => {
      if (k in mix) return '' + mix[k]
    }
    const arr = (k: string) => {
      if (!(k in mix)) return;
      const v = mix[k];
      return Array.isArray(v) ? v.map(v => '' + v) : void 0
    }
    return { str, arr }
  }, [search_str, hash_str, state, froms])
}

